package com.wjcxf.struct;

import com.wjcxf.utils.CalcUtil;

import java.util.HashSet;

public class BullsAndCows {
    long startTimeStamp = 0L;
    int guessCount = 0;
    private int[] guessNumberList = new int[4];
    private int[] answerNumberList = new int[4];

    public void init(){
        System.out.println("Game start");
        //洗牌算法
        int[] numbers = {0,1,2,3,4,5,6,7,8,9};
        for(int i = 0;i<numbers.length-1;i++){
            int rand = CalcUtil.getRandomNumber(i+1, numbers.length-1);
            numbers[i] ^= numbers[rand];
            numbers[rand] ^= numbers[i];
            numbers[i] ^= numbers[rand];
        }
        for(int i = 0;i<answerNumberList.length;i++){
            this.answerNumberList[i] = numbers[i];
//            System.out.println(this.answerNumberList[i]);
        }
        startTimeStamp = System.currentTimeMillis();
    }
    public int[] numberToList(int num){
        return new int[]{num%10,(num/10)%10,(num/100)%10,(num/1000)%10};
    }

    public void validateGuessNumber(int num){
        int []guessNumArr = numberToList(num);
        //判断每一位是否有重复
        HashSet<Integer> hashSet = new HashSet<>();
        for(int i=0;i< guessNumArr.length;i++){
            hashSet.add(guessNumArr[i]);
        }
        if(hashSet.size() != guessNumArr.length){
            System.out.println("invalid input");
            return;
        }
        for(int i = 0;i<guessNumberList.length;i++){
            this.guessNumberList[i] = guessNumArr[i];
        }

        int a = this.getACount();
        int b = this.getBCount();
        System.out.println(String.format("(%d)Your answer is %d ,(%.3f)s,result is %dA%dB",this.guessCount,num,(float)((System.currentTimeMillis() - this.startTimeStamp)/1000.0f), a,b ));

    }
    public boolean isGameOver(){
        boolean flag = true;
        for(int i = 0;i<this.guessNumberList.length;i++){
            if(this.answerNumberList[i] != this.guessNumberList[i]){
                flag = false;
                break;
            }
        }
        return flag;
    }

    private int getACount(){
        int result = 0;
        for(int i = 0;i<this.guessNumberList.length;i++){
            if(this.answerNumberList[i] == this.guessNumberList[i]){
                result++;
            }
        }
        return result;
    }
    private int getBCount(){
        int result = 0;
        for(int i = 0;i<this.guessNumberList.length;i++){
            for(int j = 0;j<this.answerNumberList.length;j++){
                if(i!=j&& this.guessNumberList[i] == this.answerNumberList[j]){
                    result++;
                }
            }
        }
        return result;
    }

}
